<?php
/**
 * Created by PhpStorm.
 * User: ruma
 * Date: 2019/1/19
 * Time: 12:23
 */

namespace app\Excepiton;


use Exception;
use think\exception\Handle;
use think\Log;

class ExceptionHandler extends Handle
{
    private $code;
    private $msg;
    private $errorCode;
    //可以添加url如果是做API开发的话

    public function render(Exception $e)
    {

        if ($e instanceof BaseException){
            //自定义异常,向客户返回具体消息
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;
        }
        else{
            //服务器端异常,不返回客户信息.
            /*在生产模式下(生产模式下取消调试模式)*/
            if (config('app_debug')){
                //执行父类(原来的)的render方法
                return parent::render($e);
            }
            else{
                //在服务端要记录日志(全局日志已经关闭)
                $this->code = 500;
                $this->msg = '服务器内部错误';
                $this->errorCode = 999;
                //开启日志系统并记录日志
                $this->recordErrorLog($e);
            }
        }
        //赋值到$result数组变量
        $result = [
            'msg' => $this->msg,
            'error_code' => $this->errorCode
        ];

//        return $result;
//        API开发的话返回json好点
        return json($result, $this->code);
    }

    //记录日志封装函数
    private function recordErrorLog(Exception $e){
        //开启日志系统
        Log::init([
            'type' => 'File',
            'path' => LOG_PATH,
            'level' => ['error']
        ]);
        Log::record($e->getMessage(), 'error');
    }

}